package com.zysc.processflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zysc.processflow.common.base.BaseService;
import com.zysc.processflow.common.util.StringUtils;
import com.zysc.processflow.entity.Attachment;
import com.zysc.processflow.entity.Brand;
import com.zysc.processflow.mapper.BrandMapper;
import com.zysc.processflow.service.IAttachmentService;
import com.zysc.processflow.service.IBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Mr.Liuyijiang
 * @Description:
 * @Date Created in 2022-06-04 20:24
 * @Modified By:
 */
@Service
public class BrandService extends BaseService<BrandMapper, Brand> implements IBrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private IAttachmentService attachmentService;

    /**
     * 根据查询条件分页并排序查询品牌信息
     *
     * @param page
     * @param key
     * @param sortBy
     * @param desc
     * @return
     */
    public List<Brand> queryBrandsByPage(IPage<Brand> page,String key,String sortBy, Boolean desc) {
        List<Brand> result = new ArrayList();
        QueryWrapper<Brand> brandQw = new QueryWrapper<>();
        brandQw.like(!StringUtils.isNull(key),"name",key);
        if(!StringUtils.isNull(sortBy)){
            brandQw.orderBy(desc!=null,!desc,sortBy);
        }
        if (page!=null){
            result = this.baseMapper.selectPage(page, brandQw).getRecords();
        }else{
            result = this.list(brandQw);
        }
        result.forEach(item->{
            List<Attachment> filesByLinkId = attachmentService.getFilesByLinkId(item.id);
            item.setAttatchments(filesByLinkId);
        });
        return result;
//
//        //添加分页条件:知识点2：这行代码必须放前边
//        //从此，不管下边怎么操作，只显示第page页的rows条信息
//        PageHelper.startPage(page,rows);
//        //初始化example对象，
//        Example example = new Example(Brand.class);
//        Example.Criteria criteria = example.createCriteria();
//        //key做模糊查询,可能根据name模糊查询，或者根据首字母查询
//        //StringUtils.isBlank :null、 ""、 "  "
//        //StringUtils.isEmpty :null、 ""
//        if(StringUtils.isNotBlank(key)){
//            //知识点1：多条件查询
//            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key);
//        }
//
//        //添加排序条件
//        if(StringUtils.isNotBlank(sortBy)){
//            //知识点example.setOrderByClause：order by id asc
//            example.setOrderByClause(sortBy+" " + (desc?"desc":"asc"));
//        }
//
//        List<Brand> brands = this.brandMapper.selectByExample(example);
//        //包装成pageInfo
//        PageInfo<Brand> brandPageInfo = new PageInfo<>(brands);
//        //包装成分页结果集返回
//        return new PageResult(brandPageInfo.getTotal(),brandPageInfo.getList());
    }

    /**
     * 新增品牌
     * @param brand
     * @param cids
     */
    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        //新增两张表
        //知识点insert两个方法的区别:
        //insert into `tb_brand`
        // (`id`, `name`, `image`, `letter`)
        // values('6522','朵唯（DOOV）','','D');
        //如果brand的image选项没传那么sql有区别
        //insert:insert into `tb_brand` (`id`, `name`, `image`, `letter`) values('6522','朵唯（DOOV）',null,'D');
        //insertSelective:insert into `tb_brand` (`id`, `name`, `letter`) values('6522','朵唯（DOOV）','D');
        //boolean flag = this.brandMapper.insert(brand) == 1;
        boolean flag = this.saveOrUpdate(brand);
        this.brandMapper.deleteCategoryAndBrand(brand.getId());
        //删除所有的brand对应的cids
        if(flag){
            cids.forEach(cid->{
                this.brandMapper.insertCategoryAndBrand(cid,brand.getId());
            });
        }
        //先新增brand表
        //再新增category_brand表
    }


    /**
     * 根据分类id查询品牌
     * @param cid
     * @return
     * 自定义sql语句
     */
    public List<Brand> queryBrandsByCid(Long cid) {

        return this.brandMapper.selectBrandsByCid(cid);
    }
}
